package com.hwd.srb.core.controller.api;


import com.hwd.srb.common.util.JwtUtils;
import com.hwd.srb.common.constant.Constants;
import com.hwd.srb.common.exception.Assert;
import com.hwd.srb.common.result.R;
import com.hwd.srb.common.result.ResponseEnum;
import com.hwd.srb.core.pojo.entity.BorrowInfo;
import com.hwd.srb.core.service.BorrowInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * <p>
 * 借款信息表 前端控制器
 * </p>
 *
 * @author 黄伟东/Victor
 * @since 2022-03-10
 */
@RestController
@RequestMapping("/api/core/borrowInfo")
@Api(tags = "借款人信息接口")
public class ApiBorrowInfoController {

    @Resource
    private BorrowInfoService borrowInfoService;

    /**
     * 获取借款申请审批状态
     * @param request 请求对象
     * @return com.hwd.srb.common.result.R
     */
    @ApiOperation("获取借款申请审批状态")
    @GetMapping("/getBorrowInfoStatus")
    public R getBorrowInfoStatus(HttpServletRequest request) {
        // 获取JWT令牌
        String token = request.getHeader(Constants.TOKEN);
        Assert.notNull(token, ResponseEnum.WEIXIN_FETCH_USERINFO_ERROR);
        // 解析令牌，获取userId
        Long userId = JwtUtils.getUserId(token);

        Integer borrowInfoStatus = borrowInfoService.getBorrowInfoStatus(userId);

        return R.ok().data("borrowInfoStatus",borrowInfoStatus);
    }

    /**
     * 提交借款申请
     *
     * @param borrowInfo 借款申请信息
     * @param request    请求对象
     * @return com.hwd.srb.common.result.R
     */
    @ApiOperation("提交借款申请")
    @PostMapping("/save")
    public R save(@ApiParam(value = "借款申请信息", required = true)
                  @RequestBody BorrowInfo borrowInfo, HttpServletRequest request) {
        // 获取JWT令牌
        String token = request.getHeader(Constants.TOKEN);
        Assert.notNull(token, ResponseEnum.WEIXIN_FETCH_USERINFO_ERROR);
        // 解析令牌，获取userId
        Long userId = JwtUtils.getUserId(token);
        borrowInfo.setUserId(userId);

        // 调用业务层方法，提交接口申请
        borrowInfoService.saveBorrowInfo(borrowInfo);

        return R.ok();
    }

    /**
     * 从请求头里获取JWT令牌token，再解析token获取userId
     * 根据userId获取当前用户接口额度
     *
     * @param request 请求对象
     * @return com.hwd.srb.common.result.R
     */
    @ApiOperation("获取借款额度")
    @GetMapping("/getBorrowAmount")
    public R getBorrowAmount(HttpServletRequest request) {
        // 获取JWT令牌
        String token = request.getHeader(Constants.TOKEN);
        Assert.notNull(token, ResponseEnum.WEIXIN_FETCH_USERINFO_ERROR);
        // 解析令牌，获取userId
        Long userId = JwtUtils.getUserId(token);

        // 调用业务层方法，根据userId获取借款额度
        BigDecimal borrowAmount = borrowInfoService.getBorrowAmount(userId);

        return R.ok().data("borrowAmount", borrowAmount);
    }

}

